<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * @author 		Funnyfox Team
 * @package 	PyroCMS
 * @subpackage 	Pro Module
 * @category 	Modules
 * @license 	Apache License v2.0
 */
class Ranking extends Public_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->helper( array('text') );
		$this->load->library('module_helper');
		$this->load->model('ranking_m');

		$how_many_news = $this->module_helper->getSetting('how_many_news');
		$this->data->posts = $this->ranking_m->posts(array('limit'=>intval($how_many_news),'category'=>'latest-news','order_by'=>'created_on','order-dir'=>'DESC'));

		$this->data->max_length_url = $this->module_helper->getSetting('max_length_url');
		$this->data->max_length_item = $this->module_helper->getSetting('max_length_item');
		$this->data->max_length_address = $this->module_helper->getSetting('max_length_address');
		$this->data->max_length_details = $this->module_helper->getSetting('max_length_details');
		$this->data->max_ranking_name = $this->module_helper->getSetting('max_ranking_name');
		$this->data->max_number_dialog_name = $this->module_helper->getSetting('max_number_dialog_name');

		//	if( null ==  $this->uri->segment(1) )
		//		redirect( site_url('ranking') );
		/*	if($this->module_helper->getSetting('is_upgrade_version') == 0){
				if($this->uri->segment(3,'') == 'tester'){
					$tokenID = $this->module_helper->getTokenId();
					$_SESSION['fb_user'] = array( 'id'=>1 , 'name'=>'Admin','tokenID'=>$tokenID ,
													'user_login_greeting'=>lang('ranking.user.login.greeting') );
					
				}
				if(isset($_SESSION['fb_user']) AND $_SESSION['fb_user']['id'] == 1){
					 
				}else{
					redirect(site_url('upgrading'));
				}
			}
		*/	
	}
/**
	public function ga_run(){

		if(ENVIRONMENT != 'local'){
			$link = mysql_connect( 'localhost', 'karapos', 'kara67r8w' );
		}else{
			$link = mysql_connect('localhost', 'root', '');
		}

		if (!$link) {
			die('Could not connect: ' . mysql_error());
		}

		if(ENVIRONMENT != 'local'){
			$db_selected = mysql_select_db( 'karapos', $link);
		}else{
			$db_selected = mysql_select_db( 'ranking', $link);
		}

		if (!$db_selected) {
			die ('Can\'t use ranking : ' . mysql_error());
		}

		include "ga.php";
		//Genetic Algorithm Object
		$ga= new GA($link);
		$ga->new_connections= $ga->get_new_connection();
		while($row = mysql_fetch_array($ga->new_connections)){
			$select_query_connection = "select * from rs_connection WHERE id=".$row['connection_id'];
			$result_connection= mysql_query($select_query_connection,$ga->db);
			$row_connection= mysql_fetch_assoc($result_connection);

			$ga->update_ranking($row_connection['upper_content_id'], $row_connection['lower_content_id']);
		}
		$ga->remove_temp_posts();
		$ga->activate_new_ranking();
		unset($ga);
	}

	public function reset(){
		$this->db->query("DELETE FROM rs_connection");
		$this->db->query("DELETE FROM rs_post");
		$this->db->query("DELETE FROM rs_temp_post");
		$this->db->query("UPDATE ff_rs_content SET `rank1` = '0',`rank2` = '0'");
		$this->db->query("UPDATE ff_users_fb SET user_ranking= NULL");
		redirect( site_url('ranking') );
	}
**/
	public function index()
	{
		$this->data->regions = $this->ranking_m->_regions( $selected_id = 0 );
		$this->data->cities = $this->ranking_m->_cities( $region_id = -1 , $selected_id = 0 );

		$this->data->new_arrival = $this->ranking_m->get_2_latest_items();
		$this->data->new_post= $this->ranking_m->get_2_new_post_connection();

		$this->data->no_rank = $this->ranking_m->get_rank_items($page=1);

		if(isset($_SESSION['fb_user']) AND isset($_SESSION['just_inserted_id']) AND $_SESSION['just_inserted_id'] != ''){
			$r = $this->db->where('id',$_SESSION['just_inserted_id'])->get('ff_rs_content')->result();
			$this->data->item_inserted = $r[0];
			unset($_SESSION['just_inserted_id']);
		}

		if(isset($_SESSION['fb_user'])){
			$this->data->user = json_encode( $_SESSION['fb_user'] );
		}

		$this->data->mode='index';
		$this->data->js = "<script type='text/javascript'>var act_sys='homepage';</script>";
		
		$this->template
			->title( lang('ranking.ranking_services') )
			->build('index', $this->data);
	}

	function search(){
		$this->data->regions = $this->ranking_m->_regions( $selected_id = intval($_GET['region']) );
		$this->data->cities = $this->ranking_m->_cities( $region_id =  intval($_GET['region']) , $selected_id= intval($_GET['city']) );
		$this->data->key= html_entity_decode($_GET['key']);

		$state= $this->ranking_m->get_region_name( intval($_GET['region']) );
		$city= $this->ranking_m->get_city_name( intval($_GET['city']) );
		$key= html_entity_decode($_GET['key']);

		switch(@$_GET['by']){
			case 'region':
				$by = 'region';break;
			case 'key':
				$by = 'key';break;
			case 'all':
			default:
				$by = 'all';break;
		}

		switch($by){
			case 'region':
				if($city != '')
					$this->data->titleF = $city;
				elseif($state != '')
					$this->data->titleF = $state;
				else
					$this->data->titleF = '';
				break;
			case 'key':
				$this->data->titleF = $key;
				break;
			case 'all':
			default:
				$this->data->titleF = '';
				break;
		}

		$this->data->search_item = ' search';
		$this->data->new_arrival = $this->ranking_m->get_2_latest_items();
		$this->data->new_post= $this->ranking_m->get_2_new_post_connection();

		$this->data->no_rank = $this->ranking_m->search_item( intval($_GET['region']), intval($_GET['city']), $key, $by );

		if(isset($_SESSION['fb_user'])){
			$this->data->user = json_encode( $_SESSION['fb_user'] );
		}

		$this->data->js = "<script type='text/javascript'>var act_sys='search';</script>";

		$this->template
			->title( lang('ranking.ranking_services') )
			->build('index', $this->data);
	}

	function my_ranking(){
		if( !isset($_SESSION['fb_user']) ){
			show_404( );
			exit();
		}

		$this->data->regions = $this->ranking_m->_regions( $selected_id = 0 );
		$this->data->cities = $this->ranking_m->_cities( $region_id = -1 , $selected_id = 0 );

		$this->data->new_arrival = $this->ranking_m->get_2_latest_items();
		$this->data->new_post= $this->ranking_m->get_2_new_post_connection();

		$this->data->no_rank = $this->ranking_m->get_my_ranking_items($_SESSION['fb_user']['id']);

		if(isset($_SESSION['fb_user'])){
			$this->data->user = json_encode( $_SESSION['fb_user'] );
		}

		$this->template
			->title( lang('ranking.ranking_services') )
			->build('index', $this->data);
	}

	public function create_new_item(){
		$tokenID = $this->uri->segment(3,'');
		if( !isset($_SESSION['fb_user']) || $tokenID != $_SESSION['fb_user']['tokenID']  ){
			show_404( );
			exit();
		}

		$this->data->regions = $this->ranking_m->_regions( $selected_id = 0 );
		$this->data->cities = $this->ranking_m->_cities( $region_id = -1 , $selected_id = 0 );
		
		$this->data->tokenID = $_SESSION['fb_user']['tokenID'];
		$this->data->user_id = $_SESSION['fb_user']['id'];
		
		$this->template
			->title( lang('ranking.ranking_services.add_item') )
			->build('add_item', $this->data);
	}

	public function authorization(){
		if($this->uri->segment(3,'') == 'tester'){
			$tokenID = $this->module_helper->getTokenId();
			$_SESSION['fb_user'] = array( 'id'=>1 , 'name'=>'Admin','tokenID'=>$tokenID ,
											'user_login_greeting'=>lang('ranking.user.login.greeting') );
			redirect('ranking');
		}

		$data = ($_POST['data']);

		$tokenID = $this->module_helper->getTokenId();

		if($data['stt'] == 'login'){
			//check if user existed in database
			$r = $this->db->where('fb_id',$data['fb_id'])->get('ff_users_fb')->result();
			if(!empty($r)){
				if($r[0]->restrict_access == 0){
					$this->db->where('id',$r[0]->id)->update('ff_users_fb',
													array('name'=>$data['user_name'], 'gender'=>$data['gender']));
					$_SESSION['fb_user'] = array( 'id'=>$r[0]->id , 'name'=>$data['user_name'],'tokenID'=>$tokenID ,
											'user_login_greeting'=>lang('ranking.user.login.greeting') );
					echo 'ok';exit();
				}else{
					if(isset($_SESSION['fb_user'])) unset($_SESSION['fb_user']);
					echo lang('ranking.user.login.reject');exit();
				}
			}else{
				$this->db->insert('ff_users_fb',
									array(	'fb_id'=>$data['fb_id'],
											'name'=>$data['user_name'],
											'gender'=>$data['gender'],
											'user_ranking'=> '' ) );

				$just_inserted_id =  $this->db->insert_id();
				$_SESSION['fb_user'] = array( 'id'=>$just_inserted_id , 'name'=>$data['user_name'],'tokenID'=>$tokenID ,
											'user_login_greeting'=>lang('ranking.user.login.greeting') );
				echo 'ok';exit();
			}
		}else{
			unset($_SESSION['fb_user']);
			echo 'ok';exit();
		}

	}

	public function aj_get_cities(){
		$region_id = intval ( $_POST['region_id'] );
		echo $this->ranking_m->_cities( $region_id , 0 );
		exit();
	}

	public function aj_check_duplicate_name(){
		$name = $_POST['name'];
		$item_id = ( isset($_POST['item_id']) ) ? intval($_POST['item_id']) : 0;

		$r = $this->db->where('name',$name)->get('ff_rs_content')->result();
		if($item_id == 0){
			if(!empty($r))
				echo 'false';
			else
				echo 'ok';
		}else{
			if( count($r) <= 1 AND $r[0]->id == $item_id ){
				echo 'ok';
			}else{
				echo 'false';
			}
		}
		exit();
	}

	public function get_connection_info(){
		$this->load->model('ranking_mproc');

		$upper_list= $_POST['upper'];
		$standard= $_POST['standard'];
		$lower_list= $_POST['lower'];

		$user_id= $_SESSION['fb_user']['id'];
		$connection_msg = array('valid'=>0,'not_valid'=>0);
		// CASE 1: A:upper_list, B:standard:::: ------- A-A-A-A-A-A: B
		$upper_arr= array_filter(explode(',', $upper_list));
		if(!empty($upper_arr)){
			$i = array();
			foreach ($upper_arr as $one){
				$this->ranking_mproc->resetConnectCountMsg();
				$msg = $this->ranking_mproc->update_connection($one, $standard, $user_id);
				$connection_msg['valid'] += $msg['valid'];
				$connection_msg['not_valid'] += $msg['not_valid'];
				$i[]=$msg;
			}

		}
		// CASE 2: A:standard, C:lower_list:::: ------- A: B-B-B-B-B-B
		$lower_arr= array_filter(explode(',', $lower_list));
		if(!empty($lower_arr)){
			foreach ($lower_arr as $one){
				$this->ranking_mproc->resetConnectCountMsg();
				$msg = $this->ranking_mproc->update_connection($standard, $one, $user_id);
				$connection_msg['valid'] += $msg['valid'];
				$connection_msg['not_valid'] += $msg['not_valid'];
			}
		}

		$stt = lang('ranking.submit.connection.msg'). ": ".$connection_msg['valid']."<br/>";
		$stt .= lang('ranking.submit.violate.msg'). ": ".$connection_msg['not_valid'];
		echo $stt;
		exit();
	}
	
	private function get_MIME_type($fileName){
		$typeUpload= array( "jpg", "jpeg", "png", "gif", "bmp" );
		
		$sExtension = substr( $fileName, ( strrpos($fileName, '.') + 1 ) ) ;
		$sExtension = strtolower( $sExtension ) ;
		
		if(
			!in_array(substr($sExtension, 0, 3), $typeUpload) && 
			!in_array(substr($sExtension, 0, 4), $typeUpload)
		) {
			return '';
		}else{
			if(in_array(strtolower(substr($sExtension, 0, 3)), $typeUpload)){
				return substr($sExtension, 0, 3);
			}else{
				return substr($sExtension, 0, 4);
			}
		}	
	}
	
	public function post_an_item(){

		if( !isset($_SESSION['fb_user']) ||
			$this->input->post('post_tokenID')!= $_SESSION['fb_user']['tokenID'] ||
			$this->input->post('post_user_id')!= $_SESSION['fb_user']['id']
		  ){
			show_404( );
			exit();
		}

		$tempPath = './uploads/files/tmp/';
		$storePath = './uploads/files/pictures/';
	
		if( ! filter_var($this->input->post('image_uploaded_1'), FILTER_VALIDATE_URL) ){
			$pic1 = $this->module_helper->uploadFile( $tempPath.$this->input->post('image_uploaded_1'),
												  $this->input->post('image_uploaded_1'),
												  $storePath,''
												);
			$this->_move_to_store_picture($tempPath.$this->input->post('image_uploaded_1'), $storePath.$pic1);
		}else{
			$sExtension = $this->get_MIME_type( $this->input->post('image_uploaded_1') ); 
			
			$tokenID = $this->module_helper->getTokenId();
			$pic_name = "pic_".time()."_".$tokenID.".".$sExtension;
			$this->download_image_from_url_to_dir($image_url= $this->input->post('image_uploaded_1'), $imgPath = $tempPath.$pic_name);
			$this->_move_to_store_picture($imgPath, $storePath.$pic_name);
			$pic1 = $pic_name;
		}
		
		if( ! filter_var($this->input->post('image_uploaded_2'), FILTER_VALIDATE_URL) ){
			$pic2 = $this->module_helper->uploadFile( $tempPath.$this->input->post('image_uploaded_2'),
												  $this->input->post('image_uploaded_2'),
												  $storePath,''
												);
			$this->_move_to_store_picture($tempPath.$this->input->post('image_uploaded_2'), $storePath.$pic2);
		}else{
			$sExtension = $this->get_MIME_type( $this->input->post('image_uploaded_2') ); 
			
			$tokenID = $this->module_helper->getTokenId();
			$pic_name = "pic_".time()."_".$tokenID.".".$sExtension;
			$this->download_image_from_url_to_dir($image_url= $this->input->post('image_uploaded_2'), $imgPath = $tempPath.$pic_name);
			$this->_move_to_store_picture($imgPath, $storePath.$pic_name);
			$pic2 = $pic_name; 
		}
		
		if( ! filter_var($this->input->post('image_uploaded_2'), FILTER_VALIDATE_URL) ){
			$pic3 = $this->module_helper->uploadFile( $tempPath.$this->input->post('image_uploaded_3'),
												  $this->input->post('image_uploaded_3'),
												  $storePath,''
												);
			$this->_move_to_store_picture($tempPath.$this->input->post('image_uploaded_3'), $storePath.$pic3);
		}else{
			$sExtension = $this->get_MIME_type( $this->input->post('image_uploaded_3') ); 
			
			$tokenID = $this->module_helper->getTokenId();
			$pic_name = "pic_".time()."_".$tokenID.".".$sExtension;
			$this->download_image_from_url_to_dir($image_url= $this->input->post('image_uploaded_3'), $imgPath = $tempPath.$pic_name);
			$this->_move_to_store_picture($imgPath, $storePath.$pic_name);
			$pic3 = $pic_name;
		}
	
		$iChoose = $_POST["image_selected"];

		$array_insert = array ( 	'name'=> $this->input->post('name_item') ,
									'dish_name'=> $this->input->post('dish_name') ,
									'region_id' => $this->input->post('region'),
									'city_id' =>  $this->input->post('city'),
									'details' =>  $this->input->post('details'),
									'url' =>  $this->input->post('user_url'),
									'main_picture' => $iChoose,
									'google_image_key'=> $this->input->post('google_image'),
									'image1' => $pic1, 'image2' => $pic2, 'image3' => $pic3,
									'created_by_id' => $this->input->post('post_user_id'),
									'created_time' => time(),'modified_time'=> time(),
									'longitude' => floatval( $this->input->post('long') ),
									'latitude' => floatval( $this->input->post('lat') ),
									'elsewhat' => $this->input->post('elsewhat')
								);
		$this->db->insert( 'ff_rs_content', $array_insert );

		$_SESSION['just_inserted_id'] = $this->db->insert_id();
		redirect( site_url('ranking') );
	}

	function update_an_item(){
		if( !isset($_SESSION['fb_user']) ||
			$this->input->post('modify_user_id')!= $_SESSION['fb_user']['id'] )
		{
			show_404( );
			exit();
		}

		$item_id = intval($this->input->post('item_id'));
		$old = $this->db->where('id',$item_id)->get('ff_rs_content')->result();

		$tempPath = './uploads/files/tmp/';
		$storePath = './uploads/files/pictures/';

		if( $this->input->post('image_uploaded_1') != $old[0]->image1 ){
			if( ! filter_var($this->input->post('image_uploaded_1'), FILTER_VALIDATE_URL) ){
				$pic1 = $this->module_helper->uploadFile( $tempPath.$this->input->post('image_uploaded_1'),
												  $this->input->post('image_uploaded_1'),
												  $storePath,''
												);
				$this->_move_to_store_picture($tempPath.$this->input->post('image_uploaded_1'), $storePath.$pic1);
			}else{
				$sExtension = $this->get_MIME_type( $this->input->post('image_uploaded_1') ); 
				
				$tokenID = $this->module_helper->getTokenId();
				$pic_name = "pic_".time()."_".$tokenID.".".$sExtension;
				$this->download_image_from_url_to_dir($image_url= $this->input->post('image_uploaded_1'), $imgPath = $tempPath.$pic_name);
				$this->_move_to_store_picture($imgPath, $storePath.$pic_name);
				$pic1 = $pic_name;
			}
		}else{
			$pic1 = $old[0]->image1;
		}

		if( $this->input->post('image_uploaded_2') != $old[0]->image2 ){
			if( ! filter_var($this->input->post('image_uploaded_2'), FILTER_VALIDATE_URL) ){
				$pic2 = $this->module_helper->uploadFile( $tempPath.$this->input->post('image_uploaded_2'),
												  $this->input->post('image_uploaded_2'),
												  $storePath,''
												);
				$this->_move_to_store_picture($tempPath.$this->input->post('image_uploaded_2'), $storePath.$pic2);
			}else{
				$sExtension = $this->get_MIME_type( $this->input->post('image_uploaded_2') ); 
				
				$tokenID = $this->module_helper->getTokenId();
				$pic_name = "pic_".time()."_".$tokenID.".".$sExtension;
				$this->download_image_from_url_to_dir($image_url= $this->input->post('image_uploaded_2'), $imgPath = $tempPath.$pic_name);
				$this->_move_to_store_picture($imgPath, $storePath.$pic_name);
				$pic2 = $pic_name; 
			}
		}else{
			$pic2 = $old[0]->image2;
		}

		if( $this->input->post('image_uploaded_3') != $old[0]->image3 ){
			if( ! filter_var($this->input->post('image_uploaded_3'), FILTER_VALIDATE_URL) ){
				$pic3 = $this->module_helper->uploadFile( $tempPath.$this->input->post('image_uploaded_3'),
												  $this->input->post('image_uploaded_3'),
												  $storePath,''
												);
				$this->_move_to_store_picture($tempPath.$this->input->post('image_uploaded_3'), $storePath.$pic3);
			}else{
				$sExtension = $this->get_MIME_type( $this->input->post('image_uploaded_3') ); 
				
				$tokenID = $this->module_helper->getTokenId();
				$pic_name = "pic_".time()."_".$tokenID.".".$sExtension;
				$this->download_image_from_url_to_dir($image_url= $this->input->post('image_uploaded_3'), $imgPath = $tempPath.$pic_name);
				$this->_move_to_store_picture($imgPath, $storePath.$pic_name);
				$pic3 = $pic_name;
			}
		}else{
			$pic3 = $old[0]->image3;
		}

		$iChoose = $_POST["image_selected"];

		$array_update = array ( 	'name'=> $this->input->post('name_item') ,
									'dish_name'=> $this->input->post('dish_name') ,
									'region_id' => $this->input->post('region'),
									'city_id' =>  $this->input->post('city'),
									'details' =>  $this->input->post('details'),
									'url' =>  $this->input->post('user_url'),
									'main_picture' => $iChoose,
									'google_image_key'=> $this->input->post('google_image'),
									'image1' => $pic1, 'image2' => $pic2, 'image3' => $pic3,
									'modified_by_id' => $this->input->post('modify_user_id'),
							//		'modified_time' => time(),
									'longitude' => floatval( $this->input->post('long') ),
									'latitude' => floatval( $this->input->post('lat') ),
									'elsewhat' => $this->input->post('elsewhat')
								);
		$this->db->where('id',$item_id)->update('ff_rs_content',$array_update);
		redirect( site_url('ranking') );
	}

	public function iF_proc_image_preview(){
		$i = intval( $this->uri->segment(3,0) ) ;

		$uploadPath = './uploads/files/tmp/';
		$conf['allowed_types'] =  array( "jpg", "jpeg", "png", "gif", "bmp" );
		$conf['max_size'] = 8000;

		if( ($_FILES["image$i"]['size']/1024) > $conf['max_size'] ){
			$image = '';
		}else{
			$image = $this->module_helper->uploadFile(
													$_FILES["image$i"]['tmp_name'],
												 	$_FILES["image$i"]['name'],
													$uploadPath,
													$conf['allowed_types']
												);
		}
		if($image != ''){
			$link = (site_url().'uploads/files/tmp/timthumb.php?w=150&h=100&zc=1&src='.
							site_url().'uploads/files/tmp/'.$image);

			$preview = "<img src='".$link."' />";

			$rs_ar	 = array('status'=>'ok','source'=>$preview,'hidden_id'=>"image_uploaded_$i",'value'=>$image);

		}else{
			$rs_ar	= array('status'=>'error','reasonwhy'=>lang('ranking.add.form.image.upload.error'),
							'hidden_id'=>"image_uploaded_$i",'value'=>'' );
		}

		echo implode('SEP_CHAR', $rs_ar);
		//echo json_encode($rs_ar);
	}

	private function _move_to_store_picture( $tempPath_File , $storePath_file ){
		//rename($tempPath_File , $storePath_file);
		@copy($tempPath_File , $storePath_file);
	}
	
	private function download_image_from_url_to_dir($image_url, $imgPath){
		$ctx = stream_context_create(array(
			'http' => array(
				'timeout' => 3
				)
			)
		);

		if( file_put_contents($imgPath, file_get_contents($image_url, 0, $ctx)) ){return true;}
		else{
			$ch = curl_init($image_url); 
			$fp = fopen($imgPath, 'wb');
			curl_setopt($ch, CURLOPT_FILE, $fp);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_exec($ch);
			curl_close($ch);
			fclose($fp);
			return true;
		}		
	}

	function update_item(){
		$item_id = intval($_GET['item_id']);
		$user_id = intval($_GET['user_id']);

		if($user_id != $_SESSION['fb_user']['id']){
			show_404( );
			exit();
		}

		$r = $this->db->where('id',$item_id)->get('ff_rs_content')->result();

		$this->data->regions = $this->ranking_m->_regions( $r[0]->region_id );
		$this->data->cities = $this->ranking_m->_cities( $region_id =$r[0]->region_id , $selected_id =$r[0]->city_id );

		$this->data->record = $r[0];
		$this->data->modify_user_id = $user_id;
		$this->data->item_id = $item_id;

		$this->template
			->title( lang('ranking.ranking_services.update_item') )
			->build('update_item', $this->data);
	}

	function readmore(){
		$page= intval($_POST['page']);
		$mode= $_POST['mode'];

		if( $mode != 'index' ) {echo 'empty';exit();}

		$arr= $this->ranking_m->get_rank_items($page);
		$arr= array_filter($arr);
		if(empty($arr)){
			echo 'empty';
		}

		$this->data->no_rank= $arr;
		$this->load->view("partial/appendContent",$this->data);
	}

	function map(){
		$this->data->lat = floatval($_GET['lat']);
		$this->data->lng = floatval($_GET['lng']);

		$this->load->view("partial/google_map_large",$this->data);
	}








	function aj_cleaning_file(){
		//tmp file
		//auto delete after 2 hours
		$tempPath = './uploads/files/tmp/';
		$storePath = './uploads/files/pictures/';
		$cache_tmp = $tempPath.'cache/';

		//remove all file in cached tmp
		if ($handle = opendir($cache_tmp)) {
		    while (false !== ($file = readdir($handle))) {
		        if(filemtime($cache_tmp.$file)+7200 < time() AND $file !='.' AND $file != '..'  ){
		        	@unlink( $cache_tmp.$file);
		        }
		    }
		    closedir($handle);
		}

		//remove all file in tmp dir
		if ($handle = opendir($tempPath)) {
		    while (false !== ($file = readdir($handle))) {
		        if(filemtime($tempPath.$file)+7200 < time() AND $file !='.' AND $file != '..' AND $file != 'timthumb.php' ){
		        	@unlink( $tempPath.$file);
		        }
		    }
		    closedir($handle);
		}

		//remove from ./uploads/files/cached
		if ($handle = opendir('./uploads/files/cache/')) {
		    while (false !== ($file = readdir($handle))) {
		        if(filemtime('./uploads/files/cache/'.$file)+7200 < time() AND $file !='.' AND $file != '..'  ){
		        	@unlink( './uploads/files/cache/'.$file);
		        }
		    }
		    closedir($handle);
		}

		//get all images from db
		$res = $this->db->get('ff_rs_content')->result();
		$img_arr = array();
		foreach($res as $one){
			$img_arr[] = $one->image1;
			$img_arr[] = $one->image2;
			$img_arr[] = $one->image3;
		}

		if ($handle = opendir($storePath)) {
		    while (false !== ($file = readdir($handle))) {
		        if(!in_array($file, $img_arr) AND $file !='.' AND $file != '..'){
		        	@unlink($storePath.$file);
		        }
		    }
		    closedir($handle);
		}

	}

	function js_author(){
		$_SESSION['fb_user'] = (isset($_SESSION['fb_user'])) ? $_SESSION['fb_user']: null;
		$user_json = json_encode($_SESSION['fb_user']);
		header("content-type:application/x-javascript");
		echo "var json_AUTHOR = $user_json;";
	}

	function js_config(){
		$max_high= intval( $this->module_helper->getSetting('max_high_ranking_post') );
		$max_low= intval( $this->module_helper->getSetting('max_low_ranking_post') );

		if($max_high < 1) $max_high = 6;
		if($max_low < 1) $max_low = 6;

		header("content-type:application/x-javascript");
		echo "var CFG_max_high_rank= $max_high;" ;
		echo "var CFG_max_lower_rank= $max_low;";
		echo "var CFG_arr_high_rank_id = new Array();";
		echo "var CFG_arr_lower_rank_id = new Array();";
		echo "var submit_violate_msg= '".lang("ranking.submit.notvalidate.msg")."';";
		echo "var title_ctrl_ranking_upper= '".lang('ranking.ctrl.upper')."';";
		echo "var title_ctrl_ranking_standard= '".lang('ranking.ctrl.standard')."';";
		echo "var title_ctrl_ranking_lower= '".lang('ranking.ctrl.lower')."';";
		echo "var title_ctrl_ranking_delete= '".lang('ranking.ctrl.delete')."';";
		
		if('local'== ENVIRONMENT){
			echo "var fbAPIid= '107762052655387';";
		}else{
			echo "var fbAPIid= '229719387072808';";
		}

	}

	function js_get_info(){
		$id = intval($_GET['id']);
		$r = $this->db->where('id',$id)->get('ff_rs_content')->result();
		$me_id = (isset($_SESSION['fb_user']))? $_SESSION['fb_user']['id'] : 0;

		$add = $this->db->query("SELECT city,name FROM `ff_cities`, `ff_regions`
								WHERE ff_cities.id=". $r[0]->city_id." AND ff_regions.id= ".$r[0]->region_id )->result();
		if(empty($add)){
			$region = "";
			$city = "";
		}else{
			$region = $add[0]->name;
			$city = $add[0]->city;
		}						
/*		$address = ucfirst($add[0]->city).'-'.ucfirst($add[0]->name);
*/
		$address = ucfirst($city);
		$name = display( $r[0]->name,$this->data->max_number_dialog_name)."<br />".display( $r[0]->dish_name,$this->data->max_number_dialog_name);
		$details = display($r[0]->details,$this->data->max_length_details);
		$urlTitle = wordwrap( display( $r[0]->url, $this->data->max_length_url), 35, "<br />", true);
		//$link_map = site_url('ranking/map/')."?lat=".$r[0]->latitude."&lng=".$r[0]->longitude;
		$q = urlencode($r[0]->details.','.$city.','.$region.'@'.$r[0]->latitude.','.$r[0]->longitude);
		$link_map = "http://maps.google.co.jp/maps?q=$q&z=14&t=m";
		
		$google_search = '<a target="_blank" href="http://www.google.co.jp/#q='.urlencode($r[0]->name).'" >'.lang('ranking.popup.seach_by_google')."</a>";
		if($urlTitle){
			$js_url = "<a target=\"_blank\" href="."{$r[0]->url}"." >".$urlTitle."</a>"."<br />".$google_search;
		}else{
			$js_url = $google_search;
		}
		header("content-type:application/x-javascript");

		echo "var JS_info_id = $id;";
		echo "var JS_info_title ='".html_entity_decode(addslashes( $name) )."';";
		echo "var JS_info_details = '".html_entity_decode(addslashes( $details) )."';";
		echo "var JS_info_address = '".html_entity_decode(addslashes( $address) )."';";
		echo "var JS_info_url = '{$js_url}';";
		echo "var JS_info_image1 ='".$r[0]->image1."';";
		echo "var JS_info_image2 ='".$r[0]->image2."';";
		echo "var JS_info_image3 ='".$r[0]->image3."';";
		echo "var JS_info_lat =".$r[0]->latitude.";";
		echo "var JS_info_lng =".$r[0]->longitude.";";
		echo "var JS_info_mofidy_id = $me_id;";
		echo "var JS_info_underMap_link= '<a target=\"_blank\" href="."{$link_map}"." >".lang('ranking.popup.seeMap')."</a>';";
	}

	function js_report_violate(){
		$item_id = intval($_GET['id']);
		$user_id = intval($_GET['user_id']);

		if($user_id != $_SESSION['fb_user']['id']){
			show_404( );
			exit();
		}

		$r = $this->db->where('item_id',$item_id)->get('ff_item_violate')->result();
		if(!empty($r)){
			$this->db->where('id',$r[0]->id)->update('ff_item_violate',
										array('item_id'=>$item_id,'user_report_id'=>$user_id,'resolve'=>'0'));
		}else{
			$this->db->insert('ff_item_violate',
										array('item_id'=>$item_id,'user_report_id'=>$user_id,'resolve'=>'0'));
		}

		$status = lang('ranking.report.violate.msg');
		header("content-type:application/x-javascript");
		echo "var JS_info_report_status= '$status';";
	}

	function fb_channel(){
		echo '<script src="http://connect.facebook.net/en_GB/all.js"></script>';
	}

}